//
//  XUFirstController.m
//  新浪微博
//
//  Created by xuwenxin on 15-4-8.
//  Copyright (c) 2015年 xuwenxin. All rights reserved.
//

#import "XUFirstController.h"
#import "XUScanController.h"
#import "XUWebViewController.h"
#import "XUMessegeModel.h"
#import "XUOuthModel.h"
#import "HMUser.h"
#import "AFNetworking/AFNetworking.h"
#import "SDWebImage/UIImageView+WebCache.h"
#import "XUMessegeCell.h"
#import "XUPhotoCollectionView.h"
#import "XURefresh.h"
#import "XUTabBar.h"

@interface XUFirstController () <XUMessegeCellDelegate>
@property (weak, nonatomic) IBOutlet XURefresh *refreshLoad;
- (IBAction)refreshlaod:(id)sender;

@property (nonatomic, strong) NSArray *messeges;
// 蒙版
@property (nonatomic, weak) UIButton *imgBtn;

@property (nonatomic, strong) NSTimer *timer;
@end

@implementation XUFirstController

// 扫描item
- (IBAction)Scan:(id)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Scan" bundle:nil];
    UITabBarController *vc = sb.instantiateInitialViewController;
    
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // 菜单按钮
    [self addlistBtn];
    
    [self startTimer];
    // 判断 "默认首页"界面有没有值 如果有值就不加载数据  如果没有值就加载数据
    if (self.manView) {
    } else {
    //
    [self addStats];
    
    [self setupLoadStatuses];
    }
    
//    self.tableView.rowHeight = UITableViewAutomaticDimension;

}
// 开启定时器
- (void)startTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(weibobadgeValue) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}
// 获取微博未读数
- (void)weibobadgeValue
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    
    XUOuthModel *account = [XUOuthModel accountFromSandbox];
    parameter[@"access_token"]= account.access_token;
    parameter[@"uid"] = account.uid;
    [manager GET:@"https://rm.api.weibo.com/2/remind/unread_count.json" parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"有%@条信息未读%@",responseObject[@"status"],[responseObject[@"status"] class]);
        NSNumber *cout = responseObject[@"status"];
        // cout.stringValue 这个也可以
        self.tabBarItem.badgeValue = [cout description];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"获取未读数失败%@",error);
    }];
}

// 设置菜单按钮
- (void)addlistBtn
{
    UIButton *img = [[UIButton alloc] init];
    [img addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [img setTitle:@"1234 " forState:UIControlStateNormal];
    [img setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [img setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [img setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
    [img sizeToFit];
    img.imageView.x = CGRectGetMaxX(img.titleLabel.frame);
    self.imgBtn = img;
    self.navigationItem.titleView = self.imgBtn;
}
// 菜单按钮的点击事件
- (void)click:(UIButton *)btn
{
    self.imgBtn.selected = YES;
    [self list];
}

// 弹出菜单
- (void)list
{
    UIButton *btnView = [[UIButton alloc] initWithFrame:[UIScreen mainScreen].bounds];
    //    btnView.backgroundColor = [UIColor grayColor];
    [btnView addTarget:self action:@selector(btnViewClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"popover_background"]];
    CGFloat imgViewX = 80;
    CGFloat imgViewY = 50;
    CGFloat imgViewW = 217;
    CGFloat imgViewH = 200;
    imgView.frame = CGRectMake(imgViewX, imgViewY, imgViewW, imgViewH);
    imgView.userInteractionEnabled = YES;
    
    UITableView *tb = [[UITableView alloc] init];
    CGFloat tbW = imgView.frame.size.width - 20;
    CGFloat tbH = imgView.frame.size.height - 25;
    tb.frame = CGRectMake(10, 15, tbW, tbH);
    
    
    [self.view.window addSubview:btnView];
    [btnView addSubview:imgView];
    [imgView addSubview:tb];
}

// 蒙版的点击事件
- (void)btnViewClick:(UIButton *)btn
{
    NSLog(@"------");
    [btn removeFromSuperview];
    self.imgBtn.selected = NO;
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.messeges.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XUMessegeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    XUMessegeModel *model = self.messeges[indexPath.row];
    cell.delegate = self;
    cell.status = model;
    return cell;
}
//获取用户数据
- (void)addStats
{
    NSLog(@"正在获取用户数据中....");
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    
    XUOuthModel *account = [XUOuthModel accountFromSandbox];
    parameter[@"access_token"]=account.access_token;
    parameter[@"uid"] = account.uid;
    [manager GET:@"https://api.weibo.com/2/users/show.json" parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSString *new = responseObject[@"profile_image_url"];
        if ([account.profile_image_url isEqualToString:new]) {
            return ;
        }
        
        account.profile_image_url = new;
        [account save];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败%@",error);
    }];
}

// 获取微博数据
- (void)setupLoadStatuses
{
    NSLog(@"正在加载stats数据...");
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    
    XUOuthModel *account = [XUOuthModel accountFromSandbox];
    parameter[@"access_token"]=account.access_token;
    [manager GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSArray *dicts = responseObject[@"statuses"];
        self.messeges = [XUMessegeModel objectArrayWithKeyValuesArray:dicts];
        if (self.messeges)
        {
        NSLog(@"成功获取到用户数据,正在刷新列表...");
        [self.tableView reloadData];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败%@",error);
    }];
}


#pragma XUMessegeDelegate
- (void)XUMessegeCellDelegateWithPhoto:(NSArray *)photos index:(NSIndexPath *)index
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"XUPhotoCollection" bundle:nil];
    XUPhotoCollectionView *vc = sb.instantiateInitialViewController;
    vc.photos = photos;
    vc.indexCount = index;
    [self presentViewController:vc animated:YES completion:nil];
}

// 更新微博
- (void)updataweibo
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    XUOuthModel *account = [XUOuthModel accountFromSandbox];
    
    XUMessegeModel *model = [self.messeges firstObject];
    parameters[@"since_id"] = model.idstr;
    parameters[@"access_token"] = account.access_token;
    __weak typeof(self) weakSelf = self;
    AFHTTPSessionManager *maneger = [AFHTTPSessionManager manager];
    [maneger GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSMutableArray *new = [NSMutableArray array];
        
        NSArray *newdicts = responseObject[@"statuses"];
        if (newdicts != nil) {
            
            NSArray *newModel = [XUMessegeModel objectArrayWithKeyValuesArray:newdicts];
            [new addObjectsFromArray:newModel];
            [new addObjectsFromArray:weakSelf.messeges];
            weakSelf.messeges = new;
            [weakSelf.tableView reloadData];
        }
        
        [weakSelf.refreshControl endRefreshing];
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor orangeColor];
        view.frame = CGRectMake(0, 44, 375, 20);
        [self.navigationController.view insertSubview:view belowSubview:self.navigationController.navigationBar];
        
        // 提醒动画
        [UIView animateWithDuration:1.0 animations:^{
            view.y = 64;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.8 animations:^{
                view.y = 44;
            } completion:^(BOOL finished) {
                [view removeFromSuperview];
            }];
        }];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
    }];

}

// 刷新加载新微博
- (IBAction)refreshlaod:(id)sender {
    NSLog(@"%s",__func__);
    
    [self updataweibo];
    
}
@end
